package com.lmm.cg.zjgcg.pages;

import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.WritableMap;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.igexin.sdk.PushManager;
import com.lmm.cg.zjgcg.BuildConfig;
import com.lmm.cg.zjgcg.MainApplication;
import com.lmm.cg.zjgcg.config.AppKey;
import com.lmm.cg.zjgcg.config.AppKeyValueUtils;
import com.lmm.cg.zjgcg.config.ReqCodeConfig;
import com.lmm.cg.zjgcg.jq.JQPrinter;
import com.lmm.cg.zjgcg.jq.Printer_define;
import com.lmm.cg.zjgcg.pages.rnplugins.CheckPrinterStatePlugin;
import com.lmm.cg.zjgcg.pages.rnplugins.ContectPrinterPlugin;
import com.lmm.cg.zjgcg.pages.rnplugins.GetConfigvaluePlugin;
import com.lmm.cg.zjgcg.pages.rnplugins.GetLocationPlugins;
import com.lmm.cg.zjgcg.pages.rnplugins.HideLoadingPlugin;
import com.lmm.cg.zjgcg.pages.rnplugins.PrinterJycxPlugin;
import com.lmm.cg.zjgcg.pages.rnplugins.PrinterPlugins;
import com.lmm.cg.zjgcg.pages.rnplugins.SetBlueTooth;
import com.lmm.cg.zjgcg.pages.rnplugins.SetConfigvaluePlugin;
import com.lmm.cg.zjgcg.pages.rnplugins.ShowLoadingPlugin;
import com.lmm.cg.zjgcg.pages.rnplugins.ToastPlugin;
import com.lmm.cg.zjgcg.pages.rnplugins.UpdateAppPlugin;
import com.lmm.cg.zjgcg.pages.rnplugins.UploadCallBack;
import com.lmm.cg.zjgcg.service.DemoIntentService;
import com.lmm.cg.zjgcg.service.DemoPushService;
import com.lmm.cg.zjgcg.service.UpdateAppMessage;
import com.lmm.cg.zjgcg.task.BaseTask;
import com.lmm.cg.zjgcg.task.TaskCallBack;
import com.lmm.cg.zjgcg.utils.BluetoothUtil;
import com.lmm.cg.zjgcg.utils.JsonParser;
import com.lmm.cg.zjgcg.utils.PrintUtil;
import com.lmm.dresswisdom.lmmframe.components.alert.AlertUtils;
import com.lmm.dresswisdom.lmmframe.components.dialog.DefaultWaitDialog;
import com.lmm.dresswisdom.lmmframe.reactnative.BaseRNActivity;
import com.lmm.dresswisdom.lmmframe.reactnative.RNJsBridgeCallAction;
import com.lmm.dresswisdom.lmmframe.reactnative.RNJsBridgeManager;
import com.lmm.dresswisdom.lmmframe.util.LogUtils;
import com.lmm.dresswisdom.lmmframe.util.ToastUtils;
import com.tencent.bugly.beta.Beta;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.ObservableEmitter;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

@Route(path = "/page/main")
public class RNMainActivity extends BaseRNActivity {

    DefaultWaitDialog defaultWaitDialog;

    public void showDefaultDialog() {
        if (defaultWaitDialog == null) {
            defaultWaitDialog = new DefaultWaitDialog(this);
        }

        if (!defaultWaitDialog.isShowing()) {
            LogUtils.write("show");
            defaultWaitDialog.ShowDialog();
        }
    }

    public void hideDefaultDialog() {
        if (defaultWaitDialog == null) {
            defaultWaitDialog = new DefaultWaitDialog(this);
        }

        if (defaultWaitDialog.isShowing()) {
            LogUtils.write("hide");
            defaultWaitDialog.HideDialog();
            defaultWaitDialog = null;
        }
    }


    String uploadType = "";//图片上传类型
    String accessToken = ""; //接口权限
    String refreshToken = "";
    String recordGuid = "";// 记录guid
    private static File tempFile; //临时图片存储文件
    private final String rootPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "cg" + File.separator;

    private MainApplication mApplication;

    /**
     * 图片上传后网络地址
     **/
    String picUrls = "";

    ReactNativePresent mPresent;

//    private BluetoothService mService = null;


    /**
     * 旧打印机
     */
    private JQPrinter printer = new JQPrinter(Printer_define.PRINTER_MODEL.ULT113x);

    public JQPrinter getPrinter() {
        return printer;
    }


    ProgressDialog pd = null;

    /**
     * 最新通用打印方法
     */
    public BluetoothSocket mSocket;
    private ProgressDialog mProgressDialog;


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }


    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPresent = new ReactNativePresent();

        mApplication = (MainApplication) getApplication();
        if (BuildConfig.DEBUG) {
            AlertUtils.showActionAlert(this, "调试", "是否跳转应用设置", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    toAppSetting();
                }
            }, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            });
        }
        initPhotoError();

        PushManager.getInstance().initialize(this.getApplicationContext(), DemoPushService.class);
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), DemoIntentService.class);

        pd = new ProgressDialog(this);
        pd.setTitle("软件更新");//设置一个标题
        pd.setMessage("正在下载当中...");//设置消息
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setCancelable(true);//这是是否可撤销/也就是这个对话框是否可以关闭
        pd.setIndeterminate(false);//设置是否是确定值
        EventBus.getDefault().register(RNMainActivity.this);

        Beta.checkUpgrade();
    }


    /**
     * 检查蓝牙状态，如果已打开，则查找已绑定设备
     *
     * @return
     */
    public boolean checkBluetoothState() {
        if (BluetoothUtil.isBluetoothOn()) {
            return true;
        } else {
            BluetoothUtil.openBluetooth(this);
            return false;
        }
    }

    /**
     * 连接打印机
     *
     * @param name
     * @param address
     */
    public void connectDevice(final String name, final String address) {
        if (address.length() > 0 && checkBluetoothState()) {
            showProgressDialog("请稍候...");
            new BaseTask<HashMap<String, String>>(new ConnectBluetooth()) {
                @Override
                public void exec(ObservableEmitter emitter) {
                    if (mSocket != null) {
                        try {
                            mSocket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
                    mSocket = BluetoothUtil.connectDevice(device);
                    if (mSocket == null || !mSocket.isConnected()) {
                        emitter.onError(new Throwable("连接打印机失败"));
                    } else {
                        HashMap<String, String> map = new HashMap<>();
                        map.put("address", address);
                        map.put("name", name);
                        emitter.onNext(map);
                        emitter.onComplete();
                    }
                }
            }.run();


        }
    }

    /**
     * 连接设备并打印
     */
    public void connectAndPrint(final String message, final String message2) {
        if (checkBluetoothState()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showProgressDialog("请稍候...");
                }
            });

            new BaseTask<HashMap<String, String>>(new ConnectAndPrint()) {

                @Override
                public void exec(ObservableEmitter emitter) {
                    if (mSocket != null) {
                        try {
                            mSocket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }


                    String address = AppKeyValueUtils.getValue(AppKey.BlueToothAddress);
                    BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
                    mSocket = BluetoothUtil.connectDevice(device);
                    if (mSocket == null || !mSocket.isConnected()) {
                        emitter.onError(new Throwable("打印失败"));
                    } else {
                        HashMap<String, String> map = new HashMap<>();
                        map.put("message", message);
                        map.put("message2", message2);
                        PrintUtil.printTest2(mSocket, message, message2);
                        emitter.onNext(map);
                        emitter.onComplete();
                    }
                }
            }.run();

        }
    }

    class ConnectBluetooth extends TaskCallBack<HashMap<String, String>> {

        @Override
        public void onSuccess(HashMap<String, String> map) {
            String address = map.get("address");
            String name = map.get("name");
            // 将信息保存起来
            AppKeyValueUtils.setValue(AppKey.BlueToothAddress, address);
            AppKeyValueUtils.setValue(AppKey.BlueToothName, name);
            WritableMap writableMap = Arguments.createMap();
            writableMap.putString("address", address);
            writableMap.putString("name", name);
            getCallBack("setBlueThooth").invoke(writableMap);
        }

        @Override
        public void onFail(String s) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mProgressDialog.dismiss();
                }
            });
            toast(s);
        }

        @Override
        public void onFinish() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mProgressDialog.dismiss();
                }
            });
        }
    }


    /**
     * 连接并打印
     */
    class ConnectAndPrint extends TaskCallBack<HashMap<String, String>> {

        @Override
        public void onSuccess(HashMap<String, String> map) {
            String printMesasge2 = map.get("message2");
            WritableMap writableMap = Arguments.createMap();
            try {
                if (TextUtils.isEmpty(printMesasge2)) {
                    getCallBack("printerCpgl").invoke(writableMap);
                } else {
                    getCallBack("printerJycx").invoke(writableMap);
                }
            } catch (Exception e) {

            }
        }

        @Override
        public void onFail(String s) {
            toast(s);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    hideProgressDialog();
                }
            });
        }

        @Override
        public void onFinish() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    hideProgressDialog();
                }
            });
        }
    }


    protected void showProgressDialog(String message) {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setCanceledOnTouchOutside(false);
            mProgressDialog.setCancelable(false);
        }
        mProgressDialog.setMessage(message);
        if (!mProgressDialog.isShowing()) {
            mProgressDialog.show();
        }
    }

    protected void hideProgressDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

    protected void toast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void messageEventBus(UpdateAppMessage event) {
        if (event.state == 0) {
            pd.setMax(event.max);
            pd.show();
        } else if (event.state == 1) {
            pd.setProgress(event.progress);
        } else if (event.state == 2) {
            pd.dismiss();
        } else if (event.state == 3) {
            //开始安装
            install(event.filePath);
        }
    }


    /**
     * APK 安装
     *
     * @param filePath
     */
    private void install(String filePath) {
        LogUtils.write("开始执行安装: " + filePath);
        File apkFile = new File(filePath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            LogUtils.write("版本大于 N ，开始使用 fileProvider 进行安装");
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(
                    RNMainActivity.this
                    , "com.lmm.cg.zjgcg.fileprovider"
                    , apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");

        } else {
            LogUtils.write("正常进行安装");
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        startActivity(intent);
    }

    @Override
    public void addPlugins() {
        new ShowLoadingPlugin(this);
        new HideLoadingPlugin(this);
        new GetConfigvaluePlugin(this);
        new SetConfigvaluePlugin(this);
        new SetBlueTooth(this);
        new PrinterPlugins(this);
        new ToastPlugin(this);
        new GetLocationPlugins(this);
        new CheckPrinterStatePlugin(this);
        new ContectPrinterPlugin(this);
        new PrinterJycxPlugin(this);
        new UpdateAppPlugin(this);

        RNJsBridgeManager.get().registerAction("microPhotoListener", new RNJsBridgeCallAction() {
            @Override
            public void call(Map<String, Object> map, Callback callback) {
                addCallBack("microPhotoListener", callback);
                text = "";
                initRecognizerDialog();
            }
        });


        RNJsBridgeManager.get().registerAction("cgPhotos", new RNJsBridgeCallAction() {
            @Override
            public void call(Map<String, Object> map, Callback callback) {
                addCallBack("cgPhotos", callback);
                String type = "";

                if (map.containsKey("type")) {
                    type = map.get("type").toString();
                }

                if (map.containsKey("fileType")) {
                    uploadType = map.get("fileType").toString();
                }

                if (map.containsKey("recordGuid")) {
                    recordGuid = map.get("recordGuid").toString();
                }

                if (map.containsKey("accessToken")) {
                    accessToken = map.get("accessToken").toString();
                }

                if (map.containsKey("refreshToken")) {
                    refreshToken = map.get("refreshToken").toString();
                }

                ArrayList<String> photoUrls = new ArrayList<>();
                if (map.get("photos") != null) {
                    List<Map<String, Object>> photos = (List<Map<String, Object>>) map.get("photos");
                    for (Map<String, Object> item : photos) {
                        photoUrls.add(item.get("url").toString());
                    }
                }

                if (!uploadType.startsWith("ocr")) {
                    ARouter.getInstance()
                            .build("/page/takechoose")
                            .withString("type", uploadType)
                            .withString("accessToken", accessToken)
                            .withString("refreshToken", refreshToken)
                            .withString("guid", recordGuid)
                            .withStringArrayList("photos", photoUrls)
                            .navigation(RNMainActivity.this, ReqCodeConfig.ReqCode_ChoosePhoto);
                } else {
                    if (!new File(rootPath).exists()) {
                        new File(rootPath).mkdirs();
                    }
                    if (type.equals("takephoto")) {
                        ARouter.getInstance().build("/page/ocr").withString("type", uploadType).navigation(RNMainActivity.this, ReqCodeConfig.ReqCode_TakePhotoOCR);
                    } else if (type.equals("choose")) {
                        choosePhoto();
                    } else {
                        ToastUtils.showToastShort("cgPhotos方法中,type参数不对");
                    }
                }
            }
        });
    }


    private void initRecognizerDialog() {
        // 1.创建RecognizerDialog对象
        RecognizerDialog mDialog = new RecognizerDialog(this, initListener);
        // 2.设置accent、language等参数
        mDialog.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        mDialog.setParameter(SpeechConstant.ACCENT, "mandarin");
        // 若要将UI控件用于语义理解，必须添加以下参数设置，设置之后onResult回调返回将是语义理解//结果
        // mDialog.setParameter("asr_sch", "1");
        // mDialog.setParameter("nlp_version", "2.0");
        // 3.设置回调接口
        mDialog.setListener(mRecognizerDialogListener);
        // 4.显示dialog，接收语音输入
        mDialog.show();
    }

    InitListener initListener = new InitListener() {
        @Override
        public void onInit(int code) {
            if (code != ErrorCode.SUCCESS) {
                Toast.makeText(RNMainActivity.this, "监听器初始化错误，错误代码=" + code,
                        Toast.LENGTH_SHORT).show();
            }
        }
    };

    String text = "";
    RecognizerDialogListener mRecognizerDialogListener = new RecognizerDialogListener() {

        @Override
        public void onResult(RecognizerResult result, boolean isLast) {
            String json = result.getResultString();
            String content = JsonParser.parseIatResult(json);
            text += content;
            LogUtils.write(text);
            if (isLast) {
                WritableMap writableMap = Arguments.createMap();
                writableMap.putString("carno", text);
                getCallBack("microPhotoListener").invoke(writableMap);
            }

        }

        @Override
        public void onError(SpeechError error) {
            Toast.makeText(RNMainActivity.this, error.getErrorDescription(),
                    Toast.LENGTH_SHORT).show();
        }
    };


    public void choosePhoto() {
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, ReqCodeConfig.ReqCode_ChoosePhotoFromAlumb);
    }

    @Override
    public String getJsRootName() {
        return "LMMAndroidApp";
    }

    @Override
    public boolean setDebug() {
        return true;
    }


    @Override
    public List<ReactPackage> setOtherPackages() {
        List<ReactPackage> res = new ArrayList<>();
        return res;
    }


    private void toAppSetting() {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        }
        startActivity(localIntent);
    }

    private void initPhotoError() {
        // android 7.0系统解决拍照的问题
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ReqCodeConfig.ReqCode_SETBlueTooth) {
            if (resultCode == RESULT_OK) {

                String address = data.getStringExtra("address");
                String name = data.getStringExtra("name");
                // 将信息保存起来
                AppKeyValueUtils.setValue(AppKey.BlueToothAddress, address);
                AppKeyValueUtils.setValue(AppKey.BlueToothName, name);

                connectDevice(name, address);
            }
        } else if (requestCode == ReqCodeConfig.ReqCode_ChoosePhotoFromAlumb) {
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();
                CompressImg(uri);
            }
        } else if (requestCode == ReqCodeConfig.ReqCode_TakePhoto) {
            if (resultCode == RESULT_OK) {
                // 直接压缩图片
                CompressImg(tempFile);
            }
        } else if (requestCode == ReqCodeConfig.ReqCode_ChoosePhoto) {
            if (resultCode == RESULT_OK) {
                String netaddress = data.getStringExtra("imgs");
                String ajbh = data.getStringExtra("ajbh");
                WritableMap writableMap = Arguments.createMap();
                writableMap.putString("imgs", netaddress);
                writableMap.putString("ajbh", ajbh);
                getCallBack("cgPhotos").invoke(writableMap);
            }
        } else if (requestCode == ReqCodeConfig.ReqCode_TakePhotoOCR) {
            if (resultCode == RESULT_OK) {
                String netaddress = data.getStringExtra("value");
                WritableMap writableMap = Arguments.createMap();
                writableMap.putString("imgs", netaddress);
                getCallBack("cgPhotos").invoke(writableMap);
            }
        }
    }


    private String getPath() {
        return rootPath;
    }

    private void CompressImg(Uri loadUri) {
        Luban.with(this)
                .load(loadUri)
                .ignoreBy(100)
                .setTargetDir(getPath())
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        LogUtils.write("start");
                    }

                    @Override
                    public void onSuccess(File file) {
                        String path = file.getPath();
                        LogUtils.write("FilePath:" + path);
                        uploadFile(file);
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtils.write(e.getMessage());
                    }
                }).launch();
    }

    private void CompressImg(File loadFile) {
        Luban.with(this)
                .load(loadFile)
                .ignoreBy(100)
                .setTargetDir(getPath())
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        LogUtils.write("start");
                    }

                    @Override
                    public void onSuccess(File file) {
                        String path = file.getPath();
                        LogUtils.write("FilePath:" + path);
                        uploadFile(file);
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtils.write(e.getMessage());
                    }
                }).launch();
    }

    private void uploadFile(File imgFile) {
        if (uploadType.equals("ocr_car")) {
            mPresent.uploadOCRCar(imgFile, new UploadCallBack() {
                @Override
                public void uploadFinish(String netaddress) {
                    ToastUtils.showToastShort(netaddress);
                    hideDefaultDialog();
                    WritableMap writableMap = Arguments.createMap();
                    writableMap.putString("imgs", netaddress);
                    getCallBack("cgPhotos").invoke(writableMap);
                }

                @Override
                public void uploadFail() {
                    hideDefaultDialog();
                    WritableMap writableMap = Arguments.createMap();
                    writableMap.putString("imgs", "");
                    getCallBack("cgPhotos").invoke(writableMap);
                }
            });
        } else if (uploadType.equals("ocr_person")) {
            mPresent.uploadOCRPerson(imgFile, new UploadCallBack() {
                @Override
                public void uploadFinish(String netaddress) {
                    ToastUtils.showToastShort(netaddress);
                    hideDefaultDialog();
                    WritableMap writableMap = Arguments.createMap();
                    writableMap.putString("imgs", netaddress);
                    getCallBack("cgPhotos").invoke(writableMap);
                }

                @Override
                public void uploadFail() {
                    hideDefaultDialog();
                    WritableMap writableMap = Arguments.createMap();
                    writableMap.putString("imgs", "");
                    getCallBack("cgPhotos").invoke(writableMap);
                }
            });
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, ReqCodeConfig.ReqCode_ENABLE_BT);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(RNMainActivity.this);
    }

//    private final Handler mHandler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            switch (msg.what) {
//                case MESSAGE_STATE_CHANGE:
//                    switch (msg.arg1) {
//                        case BluetoothService.STATE_CONNECTED:
////                            btnConn.setText(R.string.title_connected_to);
////                            btnConn.append(mConnectedDeviceName);
//                            break;
//                        case BluetoothService.STATE_CONNECTING:
////                            btnConn.setText(R.string.title_connecting);
//                            break;
//                        case BluetoothService.STATE_LISTEN:
//                        case BluetoothService.STATE_NONE:
////                            btnConn.setText(R.string.title_not_connected);
//                            break;
//                    }
//                    break;
//                case MESSAGE_WRITE:
//                    break;
//                case MESSAGE_READ:
//                    break;
//                case MESSAGE_DEVICE_NAME:
////                    mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
//                    break;
//                case MESSAGE_TOAST:
////                    if (msg.getData().getString(TOAST).equals("无法连接到打印机。")) {
////                        SharedPreferences share = getSharedPreferences(BLUETOOTH_TAG, 0);
////                        share.edit().putString(BLUETOOTH_ADDRESS, "").commit();
////                    }
//                    Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
//                            Toast.LENGTH_SHORT).show();
//                    break;
//            }
//        }
//    };

    /**
     * 监听蓝牙状态变化的系统广播
     */
//    class BluetoothStateReceiver extends BroadcastReceiver {
//
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
//            switch (state) {
//                case BluetoothAdapter.STATE_TURNING_ON:
////                    Toast.makeText( this , "蓝牙已开启" , Toas);
//                    break;
//
//                case BluetoothAdapter.STATE_TURNING_OFF:
////                    toast("蓝牙已关闭");
//                    break;
//            }
////            onBluetoothStateChanged(intent);
//        }
//    }


}

